package com.wei.frame.ui.widget;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.wei.frame.R;
import com.wei.frame.databinding.DialogLoadingBinding;

/**
 * 作者:赵若位
 * 时间:2021/6/26 21:49
 * 描述：佛祖保佑，永无BUG~
 * 功能:
 */
public class LoadingDialog implements LifecycleObserver {

    private AlertDialog mDialog;
    private Context mContext;
    private DialogLoadingBinding mBinding;

    public LoadingDialog(@Nullable Context context) {
        this.mContext = context;
        initView();
        if (null != mContext && mContext instanceof LifecycleOwner) {
            ((LifecycleOwner) mContext).getLifecycle()
                    .addObserver(this);
        }
    }

    private void initView() {
        mBinding = DialogLoadingBinding.inflate(LayoutInflater.from(mContext));
        mDialog = new AlertDialog.Builder(mContext, R.style.LoadingDialogStyle)
                .setView(mBinding.getRoot())
                .create();
        mDialog.setOnDismissListener(dialog -> dismiss());
    }

    public void showLoading() {
        if (null != mDialog) {
            mBinding.imgLoading.clearAnimation();
            mBinding.imgLoading.startAnimation(getNormalAnimation());
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }
    }


    public void dismiss() {
        if (null != mDialog) {
            if (null != mBinding) {
                mBinding.imgLoading.clearAnimation();
            }
            if (mDialog.isShowing()) {
                mDialog.dismiss();
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void dismiss(LifecycleOwner owner) {
        dismiss();
        if (null != owner && null != owner.getLifecycle()) {
            owner.getLifecycle().removeObserver(this);
        }
    }

    /*进度条旋转动画*/
    private RotateAnimation getNormalAnimation() {
        RotateAnimation animation = new RotateAnimation(0f, 360f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(800);
        animation.setRepeatCount(-1);
        animation.setFillAfter(true);
        animation.setRepeatMode(Animation.RESTART);
        //旋转动画过度平滑
        animation.setInterpolator(new LinearInterpolator());
        return animation;
    }

}
